package com.mall.common.advice;

import com.mall.common.response.CommonResponse;
import com.mall.common.annotation.IngoreResponseAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *
 * 增强--》干预
 * @author baimugudu
 * @email 616769721@qq.com
 * @date 2021/7/14 15:08
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 是否需要增强
     * @param returnType 返回类型
     * @param aClass     一个类
     * @return boolean
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        if(returnType.getDeclaringClass().isAnnotationPresent(IngoreResponseAdvice.class)){
            return false;
        }
        if(returnType.getMethod().isAnnotationPresent(IngoreResponseAdvice.class)){
            return false;
        }
        return true;
    }

    /**
     * 增强的逻辑
     * @param body 数据
     * @param returnType 返回类型
     * @param selectedContentType 内容类型
     * @param selectedConverterType 转换类型
     * @param request 所拦截请求
     * @param response 所拦截响应
     * @return Object
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        CommonResponse<Object> commonResponse = new CommonResponse<Object>(0, "success");
        if(body==null){
            return commonResponse;
        }else if(body instanceof  CommonResponse){
            commonResponse =   ( CommonResponse<Object> )body;
        }else{
            commonResponse.setData(body);
        }
        return commonResponse;
    }
}
